package com.zerosoft.villagemonitor.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zerosoft.villagemonitor.config.ZLMediaProperties;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
@Data
public class ZLMediaKitService {
//    CloseableHttpClient httpClient;
//    CloseableHttpResponse response;
    @Resource
    private ZLMediaProperties zlMediaProperties;

    /**
     *  拉流代理
     * @param url 推流的URL，从海康平台中获取
     * @param stream 流的唯一的标识，可用海康平台中的indexCode来设置
     * @return {
     *    "code" : 0,
     *    "data" : {
     *       "key" : "__defaultVhost__/proxy/0"  # 流的唯一标识
     *    }
     * }
     */
    @SneakyThrows
    public String addStreamProxy(String url, String stream) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(zlMediaProperties.getUrl() + "/index/api/addStreamProxy");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("vhost", zlMediaProperties.getVhost()));
        params.add(new BasicNameValuePair("app", zlMediaProperties.getApp()));
        params.add(new BasicNameValuePair("stream", stream));
        params.add(new BasicNameValuePair("url", url));
        params.add(new BasicNameValuePair("auto_close", "true"));
        params.add(new BasicNameValuePair("secret", zlMediaProperties.getSecret()));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            log.info("请求结果：" + response.toString());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

        }
        String retData = EntityUtils.toString(response.getEntity());
        System.out.println("retdata: "+retData);
        return retData;
    }

    /**
     * 删除拉流代理
     * @param key   addStreamProxy中返回的key
     * @return {
     *    "code" : 0,
     *    "data" : {
     *       "flag" : true # 成功与否
     *    }
     * }
     */
    @SneakyThrows
    public String delStreamProxy(String key) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(zlMediaProperties.getUrl() + "/index/api/delStreamProxy");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("key", key));
        params.add(new BasicNameValuePair("secret", zlMediaProperties.getSecret()));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            log.info("请求结果：" + response.toString());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

        }
        String retData = EntityUtils.toString(response.getEntity());
        System.out.println("retdata: "+retData);
        return retData;
    }

    /**
     * 获取流列表
     * @return
     */
    @SneakyThrows
    public String getMediaList() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(zlMediaProperties.getUrl() + "/index/api/getMediaList");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("secret", zlMediaProperties.getSecret()));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            log.info("请求结果：" + response.toString());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

        }
        String retData = EntityUtils.toString(response.getEntity());
        System.out.println("retdata: "+retData);
        return retData;
    }

    /**
     * 关闭流
     * @param app
     * @param vhost
     * @param stream
     * @param schema
     * @param force 强制关闭
     * @return
     */
    @SneakyThrows
    public String closeStreams(String app, String vhost, String stream, String schema, boolean force) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(zlMediaProperties.getUrl() + "/index/api/close_streams");
        List<NameValuePair> params = new ArrayList<>();
//        params.add(new BasicNameValuePair("app", app));
//        params.add(new BasicNameValuePair("stream", stream));
        params.add(new BasicNameValuePair("secret", zlMediaProperties.getSecret()));
        if(vhost != null)
        {
            params.add(new BasicNameValuePair("vhost", vhost));
        }
        if(schema != null)
        {
            params.add(new BasicNameValuePair("schema", schema));
        }
        if(app != null)
        {
            params.add(new BasicNameValuePair("app", app));
        }
        if(stream != null)
        {
            params.add(new BasicNameValuePair("stream", stream));
        }
        if(force)
        {
            params.add(new BasicNameValuePair("force", "true"));
        }

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            log.info("请求结果：" + response.toString());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

        }
        String retData = EntityUtils.toString(response.getEntity());
        System.out.println("retdata: "+retData);
        return retData;
    }

    public boolean isStreamExist(String stream) {
        JSONObject response = JSONObject.parseObject(getMediaList());
//        if(response.get("data")){
//
//        }
        return getMediaList().contains(stream);
    }

    public String getStreamUrl(String stream) {
        return zlMediaProperties.getFlvurl() + stream + zlMediaProperties.getFlvext();
    }
}
